using Tools.Domain.Common.Repositories.Contracts;
using Web.App.Infrastructure.ObjectStore.Contracts;
using Webshop20.Application.Operations.Messages;
using Webshop20.Domain.Customers.Core;
using Webshop20.Domain.Customers.Factories.Contracts;
using Webshop20.Domain.Security.Authentication.Core;
using Webshop20.Domain.Security.Authentication.Factories.Contracts;

namespace Webshop20.Application.Operations.Services
{
    public interface IInitializeNewRegistrationService : IService{}

    public class InitializeNewRegistrationService : ServiceBase, IInitializeNewRegistrationService
    {
        private readonly IAccountFactory accountFactory;
        private readonly ICustomerFactory customerFactory;
        private readonly IObjectStoreRepository objectStore;

        public InitializeNewRegistrationService(
                                                    IAccountFactory accountFactory, 
                                                    ICustomerFactory customerFactory,
                                                    IObjectStoreRepository objectStoreRepository
                                                )
        {
            this.accountFactory = accountFactory;
            objectStore = objectStoreRepository;
            this.customerFactory = customerFactory;
        }

        private void accountFactory_DomainFailure(DomainMessageSentEventArgs args, object sender)
        {
            domainMessage = args.SystemMessage;
        }

        public override ISystemMessage Handle(ISystemMessage request)
        {
            var newAccountRequest = request as InitializeNewRegistrationRequest;
            Account account = accountFactory.Create(newAccountRequest.EMail, newAccountRequest.Password, newAccountRequest.PasswordConfirm);
            
            if (DomainReportsFailure())
                return new InitializeNewRegistrationResponse(string.Empty, null, string.Empty);

            Customer customer = customerFactory.Create(newAccountRequest.EMail, newAccountRequest.FirstName,
                                                       newAccountRequest.LastName);

            var accountItem = objectStore.Add(account, "transient account");
            var customerItem = objectStore.Add(customer, "transient customer");
            return new InitializeNewRegistrationResponse(accountItem.Id.ToString(),null, customerItem.Id.ToString());
        }
    }
}